﻿using System;
using System.Linq;
using System.Collections.Generic;
using Eagles.Base;
using Eagles.DomainService.Model.User;
using Eagles.DomainService.Model.Activity;
using Eagles.Interface.Core.Activity;
using Eagles.Interface.Configuration;
using Eagles.Interface.DataAccess.Util;
using Eagles.Interface.DataAccess.ActivityAccess;
using Eagles.Application.Model;
using Eagles.Application.Model.Enums;
using Eagles.Application.Model.Common;
using Eagles.Application.Model.Activity.CreateActivity;
using Eagles.Application.Model.Activity.EditActivityCancel;
using Eagles.Application.Model.Activity.IsJoinActivity;
using Eagles.Application.Model.Activity.EditActivityJoin;
using Eagles.Application.Model.Activity.EditActivityReview;
using Eagles.Application.Model.Activity.EditActivityComplete;
using Eagles.Application.Model.Activity.EditActivityFeedBack;
using Eagles.Application.Model.Activity.GetActivity;
using Eagles.Application.Model.Activity.GetActivityDetail;
using Eagles.Application.Model.Activity.GetActivityFeedBack;
using Eagles.Application.Model.Activity.GetPublicActivity;
using Eagles.Application.Model.Activity.GetPublicActivityDetail;

namespace Eagles.DomainService.Core.Activity
{
    public class ActivityHandler : IActivityHandler
    {
        private readonly IActivityAccess iActivityAccess;
        private readonly IUtil util;
        private readonly IEaglesConfig configuration;

        public ActivityHandler(IActivityAccess iActivityAccess, IUtil util, IEaglesConfig configuration)
        {
            this.iActivityAccess = iActivityAccess;
            this.util = util;
            this.configuration = configuration;
        }

        public CreateActivityResponse CreateActivity(CreateActivityRequest request)
        {
            var response = new CreateActivityResponse();
            var activityId = 0;
            var fromUser = request.ActivityFromUser; //活动发起人
            var toUser = request.ActivityToUserId; //活动负责人
            var auditUserId = 0; //活动审核人
            var auditUserName = ""; //活动审核人名称
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            //因跨支部创建支部，任务支部、机构取负责人的机构、支部
            var toUserInfo = util.GetUserInfo(toUser);
            var fromUserInfo = util.GetUserInfo(fromUser);
            if (fromUserInfo == null && toUserInfo == null)
                throw new TransactionException(MessageCode.UserNotExists, MessageKey.UserNotExists);
            //找负责人的上级作为审核人
            var superior = util.GetSuperior(toUser);
            if (superior == null)
                throw new TransactionException(MessageCode.AuditUserNotExists, MessageKey.AuditUserNotExists);
            auditUserId = superior.UserId;
            auditUserName = superior.Name;
            var act = new TbActivity
            {
                ActivityId = request.ActivityId,
                OrgId = toUserInfo.OrgId,
                BranchId = toUserInfo.BranchId,
                ActivityName = request.ActivityName,
                ActivityType = request.ActivityType,
                BeginTime = request.ActivityBeginDate,
                EndTime = request.ActivityEndDate,
                HtmlContent = request.ActivityContent,
                FromUser = fromUser,
                FromUserName = fromUserInfo.Name,
                ToUserId = toUser,
                ToUserName = toUserInfo.Name,
                //0:初始状态;(上级发给下级的初始状态) -1:下级发起任务;上级审核任务是否允许开始
                Status = fromUser == auditUserId ? 0 : -1,
                CanComment = request.CanComment,
                IsPublic = request.IsPublic,
                CreateType = request.CreateType,
                ImageUrl = request.ImageUrl,
                MaxCount = 99,
                MaxUser = 99,
                OrgReview = "-1",
                BranchReview = "-1",
                AuditUserId = auditUserId,
                CreateTime = DateTime.Now
            };
            if (request.AttachList != null && request.AttachList.Count > 0)
            {
                var attachList = request.AttachList;
                for (int i = 0; i < attachList.Count; i++)
                {
                    switch (i)
                    {
                        case 0:
                            act.AttachName1 = attachList[i].AttachName;
                            act.Attach1 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 1:
                            act.AttachName2 = attachList[i].AttachName;
                            act.Attach2 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 2:
                            act.AttachName3 = attachList[i].AttachName;
                            act.Attach3 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 3:
                            act.AttachName4 = attachList[i].AttachName;
                            act.Attach4 = attachList[i].AttachmentDownloadUrl;
                            break;
                    }
                }
            }
            if (request.ActivityId > 0)
            {
                //修改
                var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
                if (activityInfo == null)
                    throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
                if (!(activityInfo.Status == 0 || activityInfo.Status == -1 || activityInfo.Status == -9))
                    throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
                var result = iActivityAccess.EditActivity(act, toUser);
                if (result <= 0)
                    throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
                activityId = request.ActivityId;
            }
            else
            {
                //新增
                var result = iActivityAccess.CreateActivity(act, toUser, out activityId);
                if (result <= 0)
                    throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            }
            //发用户通知
            var toUserNotice = new TbUserNotice()
            {
                OrgId = toUserInfo.OrgId,
                Title = "创建活动",
                Content = configuration.EaglesConfiguration.UserNoticContent
                    .Replace("${toUser}", toUserInfo.Name)
                    .Replace("${fromUser}", fromUserInfo.Name)
                    .Replace("${Action}", "发起了需要您负责的")
                    .Replace("${Content}", "“" + request.ActivityName + "”的活动"),
                TargetUrl = string.Format(configuration.EaglesConfiguration.ActivityNoticeUrl, toUserInfo.OrgId, activityId),
                //10 活动发起(上级发给下级) 11:活动申请开始(下级发给上级)
                NewsType = fromUser == auditUserId ? 10 : 11,
                FromUser = fromUser,
                UserId = toUser,
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            util.CreateUserNotice(toUserNotice);
            //如果发起人不是审核人，则给审核人发通知
            if (fromUser != auditUserId)
            {
                var toAuditUserNotice = new TbUserNotice()
                {
                    OrgId = toUserNotice.OrgId,
                    Title = toUserNotice.Title,
                    Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", auditUserName)
                        .Replace("${fromUser}", fromUserInfo.Name)
                        .Replace("${Action}", "发起了需要您审核的")
                        .Replace("${Content}", "“" + request.ActivityName + "”的活动"),
                    TargetUrl = toUserNotice.TargetUrl,
                    //10 活动发起(上级发给下级) 11:活动申请开始(下级发给上级)
                    NewsType = toUserNotice.NewsType,
                    FromUser = toUserNotice.FromUser,
                    UserId = auditUserId,
                    IsRead = toUserNotice.IsRead,
                    CreateTime = toUserNotice.CreateTime
                };
                util.CreateUserNotice(toAuditUserNotice);
            }
            return response;
        }

        public EditActivityJoinResponse EditActivityJoin(EditActivityJoinRequest request)
        {
            var response = new EditActivityJoinResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            if (activityInfo.Status != 0)
                throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
            var userActivityInfo = iActivityAccess.GetUserActivity(request.ActivityId, tokens.UserId);
            if (userActivityInfo != null && userActivityInfo.Count > 0)
                throw new TransactionException(MessageCode.JoinActivityExist, MessageKey.JoinActivityExist);
            var maxUser = activityInfo.MaxUser; //活动最大参与人数            
            var activityUserCount = iActivityAccess.GetUserActivityCount(request.ActivityId); //活动实际参与人数
            if (activityUserCount >= maxUser)
                throw new TransactionException(MessageCode.JoinActivityMax, MessageKey.JoinActivityMax);
            var userActivity = new TbUserActivity()
            {
                OrgId = tokens.OrgId,
                BranchId = tokens.BranchId,
                ActivityId = request.ActivityId,
                UserId = tokens.UserId,
                CreateTime = DateTime.Now
            };
            var result = iActivityAccess.EditActivityJoin(userActivity);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public EditActivityReviewResponse EditActivityReview(EditActivityReviewRequest request)
        {
            var response = new EditActivityReviewResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            //发用户通知
            var userNotice = new TbUserNotice()
            {
                OrgId = tokens.OrgId,
                TargetUrl = string.Format(configuration.EaglesConfiguration.ActivityNoticeUrl, tokens.OrgId, request.ActivityId),
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            switch (request.Type)
            {
                //上级审核活动
                case ActivityTypeEnum.Audit:
                    if (-1 != activityInfo.Status)
                        throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
                    if (activityInfo.AuditUserId != tokens.UserId)
                        throw new TransactionException(MessageCode.ActivityMustAudit, MessageKey.ActivityMustAudit);
                    userNotice.Title = "活动审核通过";
                    userNotice.Content = configuration.EaglesConfiguration.UserNoticContent
                                            .Replace("${toUser}", activityInfo.ToUserName)
                                            .Replace("${fromUser}", activityInfo.AuditUserName)
                                            .Replace("${Action}", "审核通过了")
                                            .Replace("${Content}", "“" + activityInfo.ActivityName + "”的活动");
                    userNotice.FromUser = activityInfo.AuditUserId;
                    userNotice.UserId = activityInfo.ToUserId;
                    userNotice.NewsType = 12; //12 活动审核通过(上级审核通过)
                    break;
                //下级申请完成活动
                case ActivityTypeEnum.Apply:
                    if (0 != activityInfo.Status)
                        throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
                    if (activityInfo.ToUserId != tokens.UserId)
                        throw new TransactionException(MessageCode.ActivityMustApply, MessageKey.ActivityMustApply);
                    userNotice.Title = "活动申请完成";
                    userNotice.Content = configuration.EaglesConfiguration.UserNoticContent
                                            .Replace("${toUser}", activityInfo.AuditUserName)
                                            .Replace("${fromUser}", activityInfo.ToUserName)
                                            .Replace("${Action}", "向您申请完成")
                                            .Replace("${Content}", "“" + activityInfo.ActivityName + "”的活动");
                    userNotice.FromUser = activityInfo.ToUserId;
                    userNotice.UserId = activityInfo.AuditUserId;
                    userNotice.NewsType = 14; //14 活动申请完成
                    break;
            }
            var result = iActivityAccess.EditActivityReview(request.Type, request.ActivityId, request.ReviewType);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            if (request.ReviewType == 0)
            {
                //发通知给审核人，如果发起人和审核人不是同一个人，则发起人也需发通知
                if (request.Type == ActivityTypeEnum.Apply && activityInfo.FromUser != activityInfo.AuditUserId)
                {
                    var fromUserNotice = new TbUserNotice()
                    {
                        OrgId = userNotice.OrgId,
                        TargetUrl = userNotice.TargetUrl,
                        IsRead = userNotice.IsRead,
                        CreateTime = userNotice.CreateTime,
                        Title = userNotice.Title,
                        Content = configuration.EaglesConfiguration.UserNoticContent
                            .Replace("${toUser}", activityInfo.FromUserName)
                            .Replace("${fromUser}", activityInfo.ToUserName)
                            .Replace("${Action}", "向您申请完成")
                            .Replace("${Content}", "“" + activityInfo.ActivityName + "”的活动"),
                        NewsType = userNotice.NewsType,
                        FromUser = userNotice.FromUser,
                        UserId = activityInfo.FromUser
                    };
                    util.CreateUserNotice(fromUserNotice);
                }
                util.CreateUserNotice(userNotice);
            }
            return response;
        }

        public EditActivityCompleteResponse EditActivityComplete(EditActivityCompleteRequest request)
        {
            var response = new EditActivityCompleteResponse();
            var score = 0; //奖励积分
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            if (activityInfo.Status != 1)
                throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
            if (activityInfo.AuditUserId != tokens.UserId)
                throw new TransactionException(MessageCode.ActivityMustComplete, MessageKey.ActivityMustComplete);
            //查询任务奖励积分
            var rewardScore = util.RewardScore(activityInfo.OrgId, "10");
            if (rewardScore != null)
                score = rewardScore.Score;
            var result = iActivityAccess.EditActivityComplete(request.ActivityId, request.IsPublic, request.CompleteStatus, score);
            if (!result)
                throw new TransactionException(MessageCode.SystemError, MessageKey.SystemError);
            //发用户通知
            var userNotice = new TbUserNotice()
            {
                OrgId = tokens.OrgId,
                NewsType = 15, //15 活动已完成
                Title = "活动完成",
                Content = configuration.EaglesConfiguration.UserNoticContent
                                    .Replace("${toUser}", activityInfo.ToUserName)
                                    .Replace("${fromUser}", activityInfo.AuditUserName)
                                    .Replace("${Action}", "审核通过了")
                                    .Replace("${Content}", "“" + activityInfo.ActivityName + "”的活动"),
                TargetUrl = string.Format(configuration.EaglesConfiguration.ActivityNoticeUrl, tokens.OrgId, request.ActivityId),
                FromUser = activityInfo.AuditUserId,
                UserId = activityInfo.ToUserId,
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            //所有参与活动的人增加积分
            var people = iActivityAccess.GetActivityJoinPeople(request.ActivityId);
            util.BatchEditUserScore(people, score); //增加所有完成活动人的积分
            foreach (var user in people)
            {
                var scoreLs = new TbUserScoreTrace()
                {
                    OrgId = tokens.OrgId,
                    UserId = user.UserId,
                    CreateTime = DateTime.Now,
                    Score = score,
                    RewardsType = "0",
                    Comment = "完成活动获得积分",
                    Source = activityInfo.ActivityName
                };
                util.CreateScoreLs(scoreLs); //增加所有完成活动人的积分流水
            }
            if (request.CompleteStatus == 0)
                util.CreateUserNotice(userNotice);
            return response;
        }

        public EditActivityFeedBackResponse EditActivityFeedBack(EditActivityFeedBackRequest request)
        {
            var response = new EditActivityFeedBackResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            if (activityInfo.Status != 0)
                throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
            if (activityInfo.ToUserId != tokens.UserId)
                throw new TransactionException(MessageCode.ActivityMustFeedBack, MessageKey.ActivityMustFeedBack);
            var feeBack = new TbUserActivity()
            {
                UserId = tokens.UserId,
                UserFeedBack = request.Content,
                ActivityId = request.ActivityId,
                FeedBackTime = DateTime.Now
            };
            if (request.AttachList != null && request.AttachList.Count > 0)
            {
                var attachList = request.AttachList;
                for (int i = 0; i < attachList.Count; i++)
                {
                    switch (i)
                    {
                        case 0:
                            feeBack.AttachName1 = attachList[i].AttachName;
                            feeBack.Attach1 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 1:
                            feeBack.AttachName2 = attachList[i].AttachName;
                            feeBack.Attach2 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 2:
                            feeBack.AttachName3 = attachList[i].AttachName;
                            feeBack.Attach4 = attachList[i].AttachmentDownloadUrl;
                            break;
                        case 3:
                            feeBack.AttachName4 = attachList[i].AttachName;
                            feeBack.Attach4 = attachList[i].AttachmentDownloadUrl;
                            break;
                    }
                }
            }
            var result = iActivityAccess.EditActivityFeedBack(feeBack);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            //发用户通知
            var userNotice = new TbUserNotice()
            {
                OrgId = tokens.OrgId,
                NewsType = 13, //13 活动负责人反馈
                Title = "活动负责人反馈",
                Content = configuration.EaglesConfiguration.UserNoticContent
                                .Replace("${toUser}", activityInfo.AuditUserName)
                                .Replace("${fromUser}", activityInfo.ToUserName)
                                .Replace("${Action}", "反馈了")
                                .Replace("${Content}", "“" + activityInfo.ActivityName + "”的活动"),
                TargetUrl = string.Format(configuration.EaglesConfiguration.ActivityNoticeUrl, tokens.OrgId, request.ActivityId),
                FromUser = activityInfo.ToUserId,
                UserId = activityInfo.AuditUserId,
                IsRead = 1,
                CreateTime = DateTime.Now
            };
            //发通知给审核人，如果发起人和审核人不是同一个人，则发起人也需发通知
            if (activityInfo.FromUser != activityInfo.AuditUserId)
            {
                var fromUserNotice = new TbUserNotice()
                {
                    OrgId = userNotice.OrgId,
                    TargetUrl = userNotice.TargetUrl,
                    IsRead = userNotice.IsRead,
                    CreateTime = userNotice.CreateTime,
                    Title = userNotice.Title,
                    Content = configuration.EaglesConfiguration.UserNoticContent
                        .Replace("${toUser}", activityInfo.FromUserName)
                        .Replace("${fromUser}", activityInfo.ToUserName)
                        .Replace("${Action}", "反馈了")
                        .Replace("${Content}", "“" + activityInfo.ActivityName + "”的活动"),
                    NewsType = userNotice.NewsType,
                    FromUser = userNotice.FromUser,
                    UserId = activityInfo.FromUser
                };
                util.CreateUserNotice(fromUserNotice);
            }
            util.CreateUserNotice(userNotice);
            return response;
        }

        public EditActivityCancelResponse EditActivityCancel(EditActivityCancelRequest request)
        {
            var response = new EditActivityCancelResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            if (activityInfo.FromUser != tokens.UserId)
                throw new TransactionException(MessageCode.ActivityMustCancel, MessageKey.ActivityMustCancel);

            var canUpdate = false;

            //发起人是上级
            if (activityInfo.FromUser == activityInfo.AuditUserId && activityInfo.Status == 0)
            {
                canUpdate = true;
            }
            else if (activityInfo.FromUser == activityInfo.ToUserId && activityInfo.Status == -1)
            {
                //下级
                canUpdate = true;
            }
            else if (activityInfo.FromUser != activityInfo.ToUserId && activityInfo.FromUser != activityInfo.AuditUserId && activityInfo.Status == -1)
            {
                //跨支部
                canUpdate = true;
            }

            if (!canUpdate)
            {
                throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
            }

            var result = iActivityAccess.EditActivityCancel(request.ActivityId);
            if (result <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetActivityFeedBackResponse GetActivityFeedBack(GetActivityFeedBackRequest request)
        {
            var response = new GetActivityFeedBackResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            var createType = activityInfo.CreateType;
            var userId = 0;
            //上级发起的活动
            if (0 == createType)
                userId = activityInfo.ToUserId;
            //下级发起的活动
            else if (1 == createType)
                userId = activityInfo.FromUser;
            var result = iActivityAccess.GetActivityFeedBack(request.ActivityId, request.AppId, userId);
            response.FeedBackList = result?.Select(x => new FeedBack
            {
                UserId = x.UserId,
                UserName = x.Name,
                UserFeedBack = x.UserFeedBack,
                FeedBackTime = x.FeedBackTime.ToString("yyyy-MM-dd"),
                AttachList = new List<Attachment>()
                {
                    new Attachment() { AttachName = x.AttachName1, AttachmentDownloadUrl = x.Attach1 },
                    new Attachment() { AttachName = x.AttachName2, AttachmentDownloadUrl = x.Attach2 },
                    new Attachment() { AttachName = x.AttachName3, AttachmentDownloadUrl = x.Attach3 },
                    new Attachment() { AttachName = x.AttachName4, AttachmentDownloadUrl = x.Attach4 }
                }
            }).ToList();
            if (result == null || result.Count <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetActivityResponse GetActivity(GetActivityRequest request)
        {
            var response = new GetActivityResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var userInfo = util.GetUserInfo(tokens.UserId);
            if (userInfo == null)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            //得到所有支部下活动
            var result = iActivityAccess.GetActivity(request.ActivityType, request.ActivityPage, userInfo, request.PageIndex, request.PageSize);
            if (result.Count == 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            response.ActivityList = result?.Select(x => new Application.Model.Common.Activity
            {
                ActivityId = x.ActivityId,
                ActivityName = x.ActivityName,
                ActivityType = x.ActivityType,
                ActivityDate = x.BeginTime.ToString("yyyy-MM-dd"),
                Status = x.Status,
                TestId = x.TestId,
                ImageUrl = x.ImageUrl
            }).ToList();
            return response;
        }

        public GetActivityDetailResponse GetActivityDetail(GetActivityDetailRequest request)
        {
            var response = new GetActivityDetailResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var result = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (result != null)
            {
                response.ActivityId = request.ActivityId;
                response.ActivityName = result.ActivityName;
                response.ActivityContent = result.HtmlContent;
                response.ActivityBeginTime = result.BeginTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.ActivityEndTime = result.EndTime.ToString("yyyy-MM-dd HH:mm:ss");
                response.ActivityImageUrl = result.ImageUrl;
                response.ActivityStatus = result.Status;
                response.InitiateUserId = result.FromUser;
                response.InitiateUserName = result.FromUserName;
                response.AcceptUserId = result.ToUserId;
                response.AcceptUserName = result.ToUserName;
                response.AuditUserId = result.AuditUserId;
                response.AuditUserName = result.AuditUserName;
                response.CreateType = result.CreateType;
                response.ActivityJoinPeopleList = iActivityAccess.GetActivityJoinPeople(request.ActivityId);

                if (tokens.UserId == result.FromUser)
                {
                    //发起人是上级
                    if (result.FromUser == result.AuditUserId && result.Status == 0)
                    {
                        response.IsUpdate = true;
                    }
                    else if (result.FromUser == result.ToUserId && result.Status == -1)
                    {
                        //下级
                        response.IsUpdate = true;
                    }
                    else if (result.FromUser != result.ToUserId && result.FromUser != result.AuditUserId && result.Status == -1)
                    {
                        //跨支部
                        response.IsUpdate = true;
                    }
                }
                else
                {
                    response.IsUpdate = false;
                }

                response.AttachmentList = new List<Attachment>
                {
                    new Attachment() {AttachName = result.AttachName1, AttachmentDownloadUrl = result.Attach1},
                    new Attachment() {AttachName = result.AttachName2, AttachmentDownloadUrl = result.Attach2},
                    new Attachment() {AttachName = result.AttachName3, AttachmentDownloadUrl = result.Attach3},
                    new Attachment() {AttachName = result.AttachName4, AttachmentDownloadUrl = result.Attach4}
                };
            }
            else
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetPublicActivityResponse GetPublicActivity(GetPublicActivityRequest request)
        {
            var response = new GetPublicActivityResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var token = request.Token;
            var tokens = util.GetUserId(request.Token, 0);
            var branchId = 0;
            if (tokens != null && tokens.UserId > 0)
            {
                branchId = tokens.BranchId;
            }
            var result = iActivityAccess.GetPublicActivity(request.AppId, false, branchId, request.PageIndex, request.PageSize);
            response.ActivityList = result?.Select(x => new Application.Model.Common.Activity
            {
                ActivityId = x.ActivityId,
                ActivityName = x.ActivityName,
                ActivityType = x.ActivityType,
                ActivityDate = x.BeginTime.ToString("yyyy-MM-dd"),
                Status = x.Status,
                TestId = x.TestId,
                ImageUrl = x.ImageUrl
            }).ToList();
            if (result == null || result.Count <= 0)
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            return response;
        }

        public GetPublicActivityDetailResponse GetPublicActivityDetail(GetPublicActivityDetailRequest request)
        {
            var response = new GetPublicActivityDetailResponse();
            if (request.AppId <= 0)
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            if (!util.CheckAppId(request.AppId))
                throw new TransactionException(MessageCode.InvalidParameter, MessageKey.InvalidParameter);
            var result = iActivityAccess.GetPublicActivityDetail(request.ActivityId, request.AppId);
            if (result != null)
            {
                response.ActivityId = request.ActivityId;
                response.ActivityName = result.ActivityName;
                response.ActivityContent = result.HtmlContent;
                response.ActivityImageUrl = result.ImageUrl;
                response.ActivityStatus = result.Status;
                response.InitiateUserId = result.FromUser;
                response.AcceptUserId = result.ToUserId;
                response.AuditUserId = result.AuditUserId;
                response.CreateType = result.CreateType;
                response.ActivityJoinPeopleList = iActivityAccess.GetActivityJoinPeople(request.ActivityId);
                response.ViewCount = result.ViewCount;
                response.AttachmentList = new List<Attachment>
                {
                    new Attachment() {AttachName = result.AttachName1, AttachmentDownloadUrl = result.Attach1},
                    new Attachment() {AttachName = result.AttachName2, AttachmentDownloadUrl = result.Attach2},
                    new Attachment() {AttachName = result.AttachName3, AttachmentDownloadUrl = result.Attach3},
                    new Attachment() {AttachName = result.AttachName4, AttachmentDownloadUrl = result.Attach4}
                };
            }
            else
            {
                throw new TransactionException(MessageCode.NoData, MessageKey.NoData);
            }
            return response;
        }

        public IsJoinActivityResponse IsJoinActivity(IsJoinActivityRequest request)
        {
            var response = new IsJoinActivityResponse();
            var tokens = util.GetUserId(request.Token, 0);
            if (tokens == null || tokens.UserId <= 0)
                throw new TransactionException(MessageCode.InvalidToken, MessageKey.InvalidToken);
            var activityInfo = iActivityAccess.GetActivityDetail(request.ActivityId, request.AppId);
            if (activityInfo == null)
                throw new TransactionException(MessageCode.ActivityNotExists, MessageKey.ActivityNotExists);
            if (activityInfo.Status != 0)
                throw new TransactionException(MessageCode.ActivityStatusError, MessageKey.ActivityStatusError);
            var userActivityInfo = iActivityAccess.GetUserActivity(request.ActivityId, tokens.UserId);
            if (userActivityInfo != null && userActivityInfo.Count > 0)
                throw new TransactionException(MessageCode.JoinActivityExist, MessageKey.JoinActivityExist);
            var maxUser = activityInfo.MaxUser; //活动最大参与人数
            var activityUserCount = iActivityAccess.GetUserActivityCount(request.ActivityId); //活动实际参与人数
            if (activityUserCount >= maxUser)
                throw new TransactionException(MessageCode.JoinActivityMax, MessageKey.JoinActivityMax);
            response.JoinCount = userActivityInfo.Count;
            return response;
        }
    }
}